// web/src/app/api/webhook/route.ts
import {NextRequest, NextResponse} from "next/server";
import {headers} from "next/headers";
import Stripe from "stripe";
import {stripe} from "@/lib/learn/stripe";
import {db} from "@/lib/db";

export async function POST(req: NextRequest) {
    const body = await req.text()
    const signature = headers().get('Stripe-Signature') as string

    let event: Stripe.Event

    try {
        event = stripe.webhooks.constructEvent(
            body, signature, process.env.STRIPE_WEBHOOK_SECRET!
        )
    } catch (err) {
        console.error('', err)
        // @ts-ignore
        return new NextResponse(`Webhook Error ${err.message}`, {status: 400})
    }

    const session = event.data.object as Stripe.Checkout.Session
    const userId = session?.metadata?.userId
    const courseId = session?.metadata?.courseId

    console.log('[WEBHOOK]')

    if (event.type === 'checkout.session.completed') {
        if (!userId || !courseId) {
            return new NextResponse(`Webhook Error: Missing metadata`, {status: 400})
        }

        // 记得运行stripe:webhook才能模拟
        console.log('[WEBHOOK] create purchase')
        await db.purchase.create({
            data: {
                courseId, userId
            }
        })
    } else {
        return new NextResponse(`Webhook Error: Unhandled event type ${event.type}`, {status: 200})
    }

    return new NextResponse(null, {status: 200})
}